//
// Created by LiuDongPeng on 2023/10/27.
//

#include "bsp.h"


/* ST HAL Lib */
#include "main.h"
#include "i2c.h"
#include "gpio.h"

/* User Hardware */
#include "button.h"
#include "as5600.h"
#include "led.h"
//#include "UserMain.h"



/**
 * @brief 控制板上的led
 */
led_t bsp_blink_led, bsp_status_led;

// 闪烁led
#define LED_BLINK_GPIO_PORT  LED_BLINK_GPIO_Port
#define LED_BLINK_GPIO_PIN   LED_BLINK_Pin

// 状态led
#define LED_STATUS_GPIO_PORT  LED_STATUS_GPIO_Port
#define LED_STATUS_GPIO_PIN   LED_STATUS_Pin

static void led_blink_set_level(uint8_t level)
{
    HAL_GPIO_WritePin(LED_BLINK_GPIO_PORT, LED_BLINK_GPIO_PIN, (level));
}
static void led_status_set_level(uint8_t level)
{
    HAL_GPIO_WritePin(LED_STATUS_GPIO_PORT, LED_STATUS_GPIO_PIN, (level));
}


/**
* @brief AS5600磁编码器
*/
as5600_t bsp_as5600;

#define AS5600_I2C_HANDLE   hi2c1

static int i2c_mem_write(uint16_t dev_addr, uint16_t mem_addr, uint16_t mem_addr_size,
                         uint8_t *buf, uint16_t btw, uint32_t timeout)
{
    return HAL_I2C_Mem_Write(&AS5600_I2C_HANDLE, AS5600_I2C_ADDRESS, mem_addr, mem_addr_size, buf, btw, timeout);
}

static int i2c_mem_read(uint16_t dev_addr, uint16_t mem_addr, uint16_t mem_addr_size,
                        uint8_t *buf, uint16_t btr, uint32_t timeout)
{
    return HAL_I2C_Mem_Read(&AS5600_I2C_HANDLE, AS5600_I2C_ADDRESS, mem_addr, mem_addr_size, buf, btr, timeout);
}




/**
 * @brief 控制板上的按键
 */
button_t bsp_btn1, bsp_btn2, bsp_btn3;

// btn1
#define BTN1_GPIO_PORT  KEY1_GPIO_Port
#define BTN1_GPIO_PIN   KEY1_Pin

// btn2
#define BTN2_GPIO_PORT  KEY2_GPIO_Port
#define BTN2_GPIO_PIN   KEY2_Pin

// btn3
#define BTN3_GPIO_PORT  KEY3_GPIO_Port
#define BTN3_GPIO_PIN   KEY3_Pin

static uint8_t get_btn1_level()
{
    return HAL_GPIO_ReadPin(BTN1_GPIO_PORT, BTN1_GPIO_PIN);
}
static uint8_t get_btn2_level()
{
    return HAL_GPIO_ReadPin(BTN2_GPIO_PORT, BTN2_GPIO_PIN);
}
static uint8_t get_btn3_level()
{
    return HAL_GPIO_ReadPin(BTN3_GPIO_PORT, BTN3_GPIO_PIN);
}










/**
 * @brief 开发板硬件外设初始化
 * @return
 */
int bsp_init()
{
    /* AS5600初始化 */
    as5600_create(&bsp_as5600, i2c_mem_write, i2c_mem_read);

    /* 按键初始化 */
    button_create(&bsp_btn1, 1, get_btn1_level);
    button_create(&bsp_btn2, 1, get_btn2_level);
    button_create(&bsp_btn3, 1, get_btn3_level);

    /* led初始化 */
    led_create(&bsp_blink_led, LED_LEVEL_HIGH, led_blink_set_level);
    led_create(&bsp_status_led, LED_LEVEL_HIGH, led_status_set_level);

    return 0;
}

/**
 * @brief 按键扫描时钟滴答，5ms调用一次
 * @return
 */
void bsp_btn_ticks()
{
    button_ticks();
}

/**
 * @brief 获取电机机械角度
 * @return
 */
float bsp_get_motor_angle()
{
    return as5600_get_angle(&bsp_as5600);
}

